
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>支付页面</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .payment-container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .section-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #333;
        }
        .address-card, .payment-card {
            background: #f9f9f9;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .address-card h5, .payment-card h5 {
            font-size: 16px;
            margin-bottom: 10px;
            color: #555;
        }
        .address-card p, .payment-card p {
            margin: 0;
            color: #777;
        }
        .btn-submit {
            width: 100%;
            padding: 10px;
            font-size: 16px;
            background-color: #ff5722;
            border: none;
            color: white;
            border-radius: 8px;
            cursor: pointer;
        }
        .btn-submit:hover {
            background-color: #e64a19;
        }
    </style>
</head>
<body>
<!-- 引入头部 -->
<div th:replace="~{fragments/header :: header(title='支付页面')}"></div>

<!-- 支付页面内容 -->
<div class="payment-container">
    <form id="orderForm" method="post" th:action="@{/order/add}">
        <!-- 地址信息 -->
        <div class="address-section">
            <div class="section-title">地址信息</div>
            <div class="address-card">
                <h5>我的地址</h5>
                <div class="address-list" th:if="${session.userAddresses == null || session.userAddresses.isEmpty()}">
                    <!-- 没有地址时显示新增地址按钮 -->
                    <button type="button" class="btn btn-primary" onclick="showAddAddressModal()">新增地址</button>
                </div>
                <div class="address-list" th:unless="${session.userAddresses == null || session.userAddresses.isEmpty()}">
                    <!-- 地址列表 -->
                    <div class="address-item" th:each="address : ${session.userAddresses}">
                        <input type="radio" name="selectedAddress" th:value="${address.id}" class="address-radio">
                        <p th:text="${address.address}"></p>
                        <p>收货人：<span th:text="${address.contact}"></span></p>
                        <p>电话：<span th:text="${address.mobile}"></span></p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 支付信息 -->
        <div class="payment-section">
            <div class="section-title">支付信息</div>
            <div class="payment-card">
                <h5>支付金额</h5>
                <span class="price-tag" th:text="'¥' + ${#numbers.formatDecimal(session.totalAmount, 1, 2)}">¥00.00</span>
            </div>
        </div>

        <!-- 提交按钮 -->
        <button type="button" class="btn-submit" onclick="submitOrder()">提交订单</button>
    </form>

    <!-- 新增地址模态框 -->
    <div class="modal fade" id="addAddressModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">新增地址</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addressForm">
                        <div class="mb-3">
                            <label for="address" class="form-label">地址</label>
                            <input type="text" name="address" class="form-control" id="address" required>
                        </div>
                        <div class="mb-3">
                            <label for="contact" class="form-label">收货人</label>
                            <input type="text" name="contact" class="form-control" id="contact" required>
                        </div>
                        <div class="mb-3">
                            <label for="mobile" class="form-label">手机号</label>
                            <input type="text" name="mobile" class="form-control" id="mobile" required>
                        </div>
                        <button type="submit" class="btn btn-primary">保存地址</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 引入 Bootstrap JS -->
<script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    // 显示新增地址模态框
    let addressModal = null; // 保存模态框实例
    function showAddAddressModal() {
        addressModal = new bootstrap.Modal(document.getElementById('addAddressModal'));
        document.getElementById('addressForm').reset(); // 清空表单
        addressModal.show();
    }

    // 处理地址表单提交
    document.getElementById('addressForm').addEventListener('submit', function(event) {
        event.preventDefault(); // 阻止默认表单提交行为

        // 获取表单数据
        const formData = new FormData(event.target);
        const params = new URLSearchParams(formData).toString(); // 转换为 URL 编码格式

        // 发起异步请求
        fetch('/address/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: params
        })
            .then(response => {
                if (response.redirected) {
                    // 如果后端返回重定向，跳转到指定页面
                    window.location.href = response.url;
                } else {
                    return response.json();
                }
            })
            .then(data => {
                if (data && data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: '添加成功',
                        text: '地址已成功添加！',
                        confirmButtonText: '确定'
                    }).then(() => {
                        // 关闭模态框并刷新页面
                        if (addressModal) addressModal.hide();
                        window.location.reload();
                    });
                } else if (data) {
                    Swal.fire({
                        icon: 'error',
                        title: '添加失败',
                        text: data.message || '地址添加失败，请稍后再试！',
                        confirmButtonText: '确定'
                    });
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: '网络错误',
                    text: '地址添加失败，请检查网络连接！',
                    confirmButtonText: '确定'
                });
            });
    });

    // 提交订单
    function submitOrder() {
        console.log('submitOrder 函数被调用'); // 日志

        // 检查是否选择了地址
        const selectedAddressElement = document.querySelector('input[name="selectedAddress"]:checked');
        if (!selectedAddressElement) {
            Swal.fire({
                icon: 'error',
                title: '地址为空',
                text: '请选择一个收货地址！',
                confirmButtonText: '确定'
            });
            return;
        }

        // 获取选中的地址 ID
        const selectedAddressId = selectedAddressElement.value;
        console.log('选中的地址 ID:', selectedAddressId);

        // 获取订单数据
        const formData = new FormData(document.getElementById('orderForm'));
        const orderData = {};
        formData.forEach((value, key) => {
            orderData[key] = value;
        });

        // 添加选中的地址 ID 到订单数据中
        orderData.selectedAddress = selectedAddressId;

        // 解析地址信息
        const selectedAddress = selectedAddressElement.closest('.address-item');
        const addressElement = selectedAddress.querySelector('p');
        const contactElement = selectedAddress.querySelector('p:nth-child(3) span');
        const mobileElement = selectedAddress.querySelector('p:nth-child(4) span');

        console.log('地址元素：', addressElement);
        console.log('收货人元素：', contactElement);
        console.log('电话元素：', mobileElement);

        if (addressElement && contactElement && mobileElement) {
            orderData.address = addressElement.textContent;
            orderData.contact = contactElement.textContent;
            orderData.mobile = mobileElement.textContent;

            console.log('地址：', orderData.address);
            console.log('收货人：', orderData.contact);
            console.log('电话：', orderData.mobile);
        } else {
            console.error('地址信息解析失败：未找到匹配的元素');
            Swal.fire({
                icon: 'error',
                title: '地址信息错误',
                text: '无法解析地址信息，请检查地址格式！',
                confirmButtonText: '确定'
            });
            return;
        }

        // 发起异步请求
        fetch('/order/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(orderData)
        })
            .then(response => {
                console.log('请求响应：', response); // 日志
                return response.json();
            })
            .then(data => {
                console.log('响应数据：', data); // 日志
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: '提交成功',
                        text: '订单已成功提交！',
                        confirmButtonText: '确定'
                    }).then(() => {
                        console.log('跳转到支付成功页面：', '/payment_ok.html'); // 日志
                        window.location.href = '/payment_ok.html';
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: '提交失败',
                        text: data.message || '订单提交失败，请稍后再试！',
                        confirmButtonText: '确定'
                    });
                }
            })
            .catch(error => {
                console.error('请求失败：', error); // 日志
                Swal.fire({
                    icon: 'error',
                    title: '网络错误',
                    text: '订单提交失败，请检查网络连接！',
                    confirmButtonText: '确定'
                });
            });
    }
</script>
</body>
</html>